<?php
	session_start();
	require_once('inc/fnc.php');
	require_once('inc/settings.php');
	include('inc/insertip.php');
	
	//Twitter oauth
	include_once('oauth/twitteroauth/EpiCurl.php');
	include_once('oauth/twitteroauth/EpiOAuth.php');
	include_once('oauth/twitteroauth/EpiTwitter.php');

	//Unsetting session stored with time when notification was last loaded (session unset on every page load)
	unset($_SESSION['notitime']);
	
	$_SESSION['time'] = time();																	//Setting time for ajax notification call
	if(isset($_GET['login'])){ if($_GET['login'] == 1){ unset($_SESSION['visitor']); } }		//
	if(isset($_GET['page'])){ $pageType = $_GET['page']; } else { $pageType = "splash"; }			//Getting page type
	if(isset($_GET['id'])) { $id = $_GET['id']; $_SESSION['sid'] = $id; } else { $id = NULL; }  //Getting id for the page type
	if(isset($_GET['title'])) { $storyTitle = $_GET['title']; } else { $storyTitle = false; } //Get story title
	if(isset($_GET['visitor'])) { if($_GET['visitor'] == 1){ $_SESSION['visitor'] = 1; } }
	
	if($pageType == 'fbapp') { redirect_to('fbapp.php'); }

	//Check cookie for remember me
	if(isset($_COOKIE["uid"]) && isset($_COOKIE["identifier"]) && isset($_COOKIE["token"])){ 
		$uid = $_COOKIE["uid"];
		$identifier = $_COOKIE["identifier"];
		$token = $_COOKIE["token"];
		
		if(authenticateCookie($uid, $identifier, $token)){
			if(!($_GET['login'] == 'true')){
				$newToken = genRandomString(45);
				if(updateCookie($uid, $identifier, $newToken)) {	
					setcookie('uid', $uid, time()+60*60*24*30, "/");			//Cookie Expiration time set to 1 month from now
					setcookie('identifier', $identifier, time()+60*60*24*30, "/");
					setcookie('token', $newToken, time()+60*60*24*30, "/" );
				} else {
					//Resetting remember me cookie failed
				}
			}
			$_SESSION['login'] = TRUE;
			$_SESSION['user'] = getUsername($uid);
			$_SESSION['userId'] = $uid;
		}
	}

	if(isset($_GET['profile'])){																// older URL structure (check and remove)
		//Do something
	} elseif(isset($_GET['type']) && isset($_session['sid'])) {
		$pageType = $_GET['type'];
		$pageId = $_session['sid'];
	}
	
	if(isset($_SESSION['userId'])) {															//Getting username from userID
		$query = "SELECT * FROM `users` WHERE userid = " . $_SESSION['userId'] . " and `delete flag` = 'N' LIMIT 1";
		$result = mysql_query( $query, $connection);
		if(!$result) { die("User authorization failed " . mysql_error()); }
		if (mysql_num_rows($result) == 1) { while($row = mysql_fetch_array($result)) { $_SESSION['username'] = $row['usrname']; } }		//If user is valid (authorized)
	}
	
	if($_GET['story']){ $storyId = $_GET['story']; }
	
	// Setting story ID so as to retrieve the specific story
	if((isset($_GET['story'])) && (isset($_SESSION['userId']))){	
		// Checking if this user has voted to any of the temp lines 
		//(used to identify which line he has voted so that the 'voteUp' button keeps highlighted)
		$query = "SELECT * FROM story WHERE id = {$_SESSION['userId']} AND storyid = {$pageId} LIMIT 1";
		$result = mysql_query( $query, $connection);
		if(!$result) { die("Failed retrieving existing user Meta info " . mysql_error()); }
		if (mysql_num_rows($result) == 1) {
			// Getting the line id (something of the form 'newline2') so that in the temp (added) lines lists, 
			// the button matching with this will be shown as the line voted previously
			while($row = mysql_fetch_array($result)){ $_SESSION['votedLineId'] = $row['vtdLneId']; }
		} else {
			// Setting the session as NULL so that earlier session value doesnt affect the result
			$_SESSION['votedLineId'] = "";
		}
	}
	
	
	
	//Check whether a page exists or not
	if($pageType == 'story') {
		if(is_numeric($id)) {
			$pagequery = mysql_query("select * from story where storyid = {$id} and delflag = 'N'");
			if(!mysql_num_rows($pagequery)) { $pageerror = 1; }
			
			//compare title
			if(isset($storyTitle)){
				while($rows = mysql_fetch_array($pagequery)){
					if(!($storyTitle == getStoryTitle($id))) {
						$pageerror = 1;
					}
				}
			} else {
				$pageerror = 1;
			}
		} else {
			$pageerror = 1;
		}
	} elseif($pageType == 'activate') {		
		//$id set at top
		//$storyTitle is the random key generated
		
		$query = "SELECT * FROM users u, activate a WHERE u.email = a.email AND a.rand = '{$storyTitle}' AND u.uniqueid = {$id} ORDER BY u.time DESC LIMIT 1";
		$result = mysql_query($query, $connection);
		if($result) {
			$row = mysql_fetch_array($result);
			$result = mysql_query("UPDATE users SET `email varification` = 'Y' WHERE userid = {$row['userid']}");
			
			if($result){
				$_SESSION['login'] = TRUE; 
				$_SESSION['invite'] = true;
				
				$_SESSION['user'] = $row['usrname'];
				$_SESSION['userId'] = $row['userid'];
				$activation = true;
			} else {
				$activation = false;
			}
		}
	} else {
		$pageerror = 0;
	} 
?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Next Twist <?php  if($pageType == 'story') { echo ": " . getStoryTitleNormal($id); } ?></title>
<meta name="description" content="Next Twist is a fun hangout that crowdsources creativity and facilitates social networking based on shared interests. Users contribute sentences to write a 100 posts long story. Story lines are crowd-conjured and chosen by the community. Engaging stories full of twists are born in real time." />

<!-- Facebook Open Graph Protocol -->
<meta property="og:type" content="website" /> 
<meta property="og:title" content="Next Twist" /> 
<meta property="og:image" content="http://www.nexttwist.com/img/nexttwist.png" /> 
<meta property="og:description" content="Next Twist is a fun hangout that crowdsources creativity and facilitates social networking based on shared interests. Users contribute sentences to write a 100 posts long story. Story lines are crowd-conjured and chosen by the community. Engaging stories full of twists are born in real time." /> 
<meta property="og:url" content="http://www.nexttwist.com/">


<!-- Here goes the CSS -->
<link rel="stylesheet" href='<?php echo DOMAIN; ?>/css/style.min.css' type="text/css"/>
<link rel="shortcut icon" href="<?php echo DOMAIN; ?>/img/favicon.ico" type="image/x-icon"/> 

<!-- Google analytics -->
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-30593463-1']);
  _gaq.push(['_setDomainName', 'nexttwist.com']);
  _gaq.push(['_setAllowLinker', true]);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>